package com.old.interceptors;


import com.alibaba.fastjson.JSONObject;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.old.service.UserService;
import com.old.util.JwtUtil;
import com.old.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final UserService userService;

    //preHandle：请求到达接口之前执行，afterCompletion：请求（接口）结束后执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
//            String username = (String) claims.get("username");
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (TokenExpiredException tx) {
            //token过期
            DecodedJWT expiredJwt = JWT.decode(token); // 直接解码，不验证签名和过期时间
            Map<String, Claim> claims = expiredJwt.getClaims();
            //遍历claims，输出里面的内容
            String claimsStr = claims.get("claims").toString();
            //claimsStr {"id":9,"avatar":"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png","username":"钟离玉梅"}
            // 将字符串解析为 JSONObject
            JSONObject jsonObject = JSONObject.parseObject(claimsStr);
            // 获取 id
            int id = jsonObject.getIntValue("id");

            userService.updateOnlineStatusToFalse(id);
            response.setStatus(401);
            //不放行
            return false;

        } catch (Exception e) {


            response.setStatus(401);
            //不放行
            return false;
        }



    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除线程存的数据
        ThreadLocalUtil.remove();
    }
}
